#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time   :2025/7/1310:08
@Author : zengjiahao1989@gmail.com
@File   :app_handler.py
"""
import os
from dataclasses import dataclass
from uuid import UUID

from injector import inject
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

from internal.exception import FailException
from internal.schema.app_schema import CompletionReq
from internal.service import AppService
from pkg.response import validate_error_json, success_message, success_json


@inject
@dataclass
class AppHandler:
    """应用控制"""
    app_service: AppService

    def create_app(self):
        """调用服务创建新的APP记录"""
        app = self.app_service.create_app()
        return success_message(f"应用已经成功创建，id为{app.id}")

    def get_app(self, id: UUID):
        app = self.app_service.get_app(id)
        return success_message(f"应用已经成功获取，名字为{app.name}")

    def update_app(self, id: UUID):
        app = self.app_service.update_app(id)
        return success_message(f"应用已经成功修改，修改为{app.name}")

    def delete_app(self, id: UUID):
        app = self.app_service.delete_app(id)
        return success_message(f"应用已经成功删除，id为{app.id}")

    # def completion(self):
    #     """聊天接口"""
    #     # 1.提取从接口中获取的输入，GET?POST?
    #     req = CompletionReq()
    #     if not req.validate():
    #         return validate_error_json(req.errors)
    #
    #     prompt = ChatPromptTemplate.from_template("{query}")
    #     # query = req.json.get("query")
    #     # 2.构建OpenAi客户端，并发起请求
    #     # client = OpenAI(base_url=os.getenv("OPENAI_API_BASE"))
    #     llm = ChatOpenAI(
    #         model_name="kimi-k2-0711-preview",
    #         openai_api_key=os.getenv("OPENAI_API_KEY"),
    #         openai_api_base=os.getenv("OPENAI_API_BASE"),
    #     )
    #     # client = OpenAI(
    #     #     api_key="sk-qdDNkQKPXskWKPs2uTAAKYMIxW0fsEgLDeS4VkWfHWluf7Y5",
    #     #     # <--在这里将 MOONSHOT_API_KEY 替换为你从 Kimi 开放平台申请的 API Key
    #     #     base_url="https://api.moonshot.cn/v1",
    #     #     # <-- 将 base_url 从 https://api.openai.com/v1 替换为 https://api.moonshot.cn/v1
    #     # )
    #     # 3.得到请求响应，然后将OpenAi的响应传递给前端
    #     ai_message = llm.invoke(prompt.invoke({"query": req.query.data}))
    #     parser = StrOutputParser()
    #     # completion = client.chat.completions.create(
    #     #     model="kimi-k2-0711-preview",
    #     #     messages=[
    #     #         {"role": "system", "content": "你是OpenAi开发的聊天机器人，请根据用户的输入回复对应的信息"},
    #     #         {"role": "user", "content": req.query.data},
    #     #     ]
    #     # )
    #     # 4.解析响应内容
    #     content = parser.invoke(ai_message)
    #     # content = completion.choices[0].message.content
    #     # resp = Response(code=HttpCode.SUCCESS, message="", data={"content": content})
    #     # 序列化resp
    #     return success_json({"content": content})

    # Runnable可运行改写
    def debug(self, app_id: UUID):
        """聊天接口"""
        # 1.提取从接口中获取的输入，GET?POST?
        req = CompletionReq()
        if not req.validate():
            return validate_error_json(req.errors)

        # 2.构建组件
        prompt = ChatPromptTemplate.from_template("{query}")
        llm = ChatOpenAI(
            model_name="kimi-k2-0711-preview",
            openai_api_key=os.getenv("OPENAI_API_KEY"),
            openai_api_base=os.getenv("OPENAI_API_BASE"),
        )
        parser = StrOutputParser()

        # 3.构建链
        chain = prompt | llm | parser

        # 4.调用链得到结果
        content = chain.invoke({"query": req.query.data})
        return success_json({"content": content})

    def ping(self):
        # return {'ping': 'pong'}
        raise FailException("数据没找到")
